import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import DataBase from 'src/config/database';
import { DeleteResult, Not, Repository, UpdateResult } from 'typeorm';
import { VideoTag } from '../videoTag/videoTag.entity';
import { Tags } from './tags.entity';


@Injectable()
export class TagsService {
  constructor(
    @InjectRepository(Tags)
    private repository: Repository<Tags>,
    @InjectRepository(VideoTag)
    private videoTagrepository: Repository<VideoTag>,
  ) {}

  findAll(): Promise<Tags[]> {
    return this.repository.find();
  }

  async findAll_By_User(user_id: number, skip: number, take: number, keyword: string): Promise<{data: Tags[],total: number}> {
    let dataList = await this.repository.query(`
      select *,
      (
        select group_concat(tag,':',id) from tags
        where parentId = a.id
      ) tag_childrens
      from tags a
      where user_id = ? and parentId = 0 and a.tag like ?
      order by create_time asc
      limit ?,?
    `,[user_id, `%${keyword}%`, skip, take]);
    let total = await this.repository.count({where:{user_id:user_id}})
    return {
      data:dataList,
      total:total
    }
  }

  findAll_By_User_NoPage(): Promise<Tags[]> {
    return this.repository.query(`
      select *,
      (
        select group_concat(tag,':',id) from tags
        where parentId = a.id
      ) tag_childrens
      from tags a
      where parentId = 0
      order by create_time desc
    `,[]);
  }
  

  findAll_By_ParentId(parentId: number, tag_childs?: []): Promise<Tags[]> {
    if(tag_childs){
      return this.repository
        .createQueryBuilder("tags")
        .select(`*`)
        .where("id not in (:...ids) and parentId = :parentId", { ids: tag_childs, parentId })
        .getRawMany()
    }else{
      return this.repository.find({where:{parentId:parentId}});
    }
  }

  findOne(id: any): Promise<Tags> {
    return this.repository.findOne(id);
  }

  async remove(id: number): Promise<DeleteResult> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //删除视频和标签的关联
      await this.videoTagrepository.createQueryBuilder(null,queryRunner).delete().where({tag_id:id}).execute()
      //删除子标签
      await this.repository.createQueryBuilder(null,queryRunner).delete().where({parentId:id}).execute()
      //删除标签
      await this.repository.createQueryBuilder(null,queryRunner).delete().where({id}).execute()
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async create(cats: Tags): Promise<void> {
    await this.repository.save(cats);
  }

  update(id: number, tag: string): Promise<UpdateResult>{
    return this.repository.update({id:id},{tag:tag})
  }

  findIsExists(tag: string) {
    return this.repository.findOne({where:{tag:tag}});
  }
}
